/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.ktx;

import com.bytedance.scene.Scene;
import com.bytedance.scene.group.GroupScene;

public class GroupSceneExtensions {
    private GroupSceneExtensions(){}

    public static void show(GroupScene groupScene, String tag) {
        Scene scene = groupScene.findSceneByTag(tag);
        if (scene != null) {
            groupScene.show(scene);
        }
    }

    public static void hide(GroupScene groupScene, String tag) {
        Scene scene = groupScene.findSceneByTag(tag);
        if (scene != null) {
            groupScene.hide(scene);
        }
    }

    public static void remove(GroupScene groupScene, String tag) {
        Scene scene = groupScene.findSceneByTag(tag);
        if (scene != null) {
            groupScene.remove(scene);
        }
    }

    public static void addAndHide(GroupScene groupScene, int componentId, Scene scene, String tag) {
        groupScene.beginTransaction();
        groupScene.add(componentId, scene, tag);
        groupScene.hide(scene);
        groupScene.commitTransaction();
    }

    public static void replace(GroupScene groupScene, int componentId, Scene scene, String tag) {
        replace(groupScene, componentId, scene, tag, 0);
    }

    public static void replace(GroupScene groupScene, int componentId, Scene scene, String tag, int animationResId) {
        Scene previousScene = groupScene.findSceneByTag(tag);
        if (previousScene == scene) {
            return;
        }

        if (groupScene.isAdded(scene)) {
            groupScene.remove(scene);
        }

        if (previousScene == null) {
            groupScene.add(componentId, scene, tag, null);
            return;
        }

        if (groupScene.isShow(previousScene)) {
            groupScene.remove(previousScene);
            groupScene.add(componentId, scene, tag, null);
        } else {
            groupScene.remove(previousScene);
            addAndHide(groupScene, componentId, scene, tag);
        }
    }

}

